<template>
  <div class="app-container">
    <div class="filter-container" align="center">
      <el-form :inline="true" :model="pageInfo" class="demo-form-inline">

        <el-form-item label="书名">
          <el-input v-model="pageInfo.bookName" placeholder="书名" />
        </el-form-item>

        <el-form-item label="类型" width="100">
          <el-select v-model="category" placeholder="类型"  >
            <el-option
              v-for="item in options"
              :key="item.category"
              :label="item.category"
              :value="item.category">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="书籍状态">
          <el-select v-model="pageInfo.intestate" placeholder="请选择">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="用户余额">-->
<!--          <el-input v-model="pageInfo.money" placeholder="用户余额" />-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" class="filter-item" icon="el-icon-search" @click="onSubmit">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="filter-item" icon="el-icon-edit" @click="onAdd">添加书籍</el-button>
        </el-form-item>


      </el-form>
    </div>
    <el-table :data="book" border style="width: 100%" stripe>
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="40">
      </el-table-column>
      <el-table-column label="图片" align="center" width="120">
        <template slot-scope="scope">
          <img :src="'/api'+scope.row.path" width="60px" height="60px">
        </template>
      </el-table-column>
      <el-table-column
        prop="bookName"
        label="书名"
        width="100"
        align="center"
      />
      <el-table-column
        prop="author"
        label="作者"
        width="100"
        align="center"
      />
      <el-table-column
        prop="introduce"
        label="简介"
        width="160"
        align="center"
      />
      <el-table-column
        prop="category"
        label="类别"
        width="80"
        align="center"
      />
<!--      <el-table-column-->
<!--        prop="read"-->
<!--        label="阅读量"-->
<!--        width="80"-->
<!--        align="center"-->
<!--      />-->
      <el-table-column label="书籍状态" align="center" :formatter="sta2" width="100">
      </el-table-column>


      <el-table-column label="会员" align="center" :formatter="sta" width="100">
      </el-table-column>


      <el-table-column label="操作" align="center">
        <!--                          获取每一次循环时 的元素节点 (v-for) user in users 中的 user    -->
        <template slot-scope="scope">
<!--          添加书架-->
          <el-button
            size="mini"
            type="warning" icon="el-icon-star-off" circle
            @click="handleAdd(scope.$index, scope.row)"
          />

<!--          修改-->
          <el-button
            size="mini"
            type="primary" icon="el-icon-edit" circle
            @click="handleEdit(scope.$index, scope.row)"
          ></el-button>
<!--          删除-->
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete" circle
            @click="handleDelete(scope.$index, scope.row)"
          ></el-button>
        </template>


      </el-table-column>
    </el-table>

    <!--    分页组件-->
    <el-pagination
      background
      :page-size="pageInfo.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      :current-page="pageInfo.pageNum"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>


<script>
import axios from "axios";

export default {
  name: "UserMoneyView",
  data() {
    return {
      total: 0,
      pageInfo: {
        pageNum: 1,
        pageSize: 5,
        bookName:"",

      },
      book: [],
      options:[],
      category:"",

      bookshelf:2,

      //加入书架的付款状态
      orderState:1,

      //判断书籍是否在订单里面
      isOrder:0,

      //书籍的id
      bookIds:[],
      user:{
        id:'',
        username:'',
      },
    }

  },
  // 前置执行方法在执行之前    beforeCreate()   axios.post(get)("http://localhost:8080/queryAll").then(...)
  created() { // 这是可以获取data中的数据后  再执行下面的axios
    this.getData()
  },
  methods: {
    sta(row) {
      if (row.vip == 1) {
        return '普通书籍'
      } else {
        return 'Vip书籍'
      }
    },
    sta2(row) {
      if (row.intestate == 1) {
        return '上架'
      } else {
        return '下架'
      }
    },
    // sta2(row){
    //   var arr=[]
    //   var roles=row.roleList
    //   for (const key in roles) {
    //     arr.push(roles[key].name)
    //   }
    //   return arr.join(",")
    // },

    //添加到书架
    handleAdd(index, row) {
      // alert(row.id)
      var userid=this.user.id
      this.$confirm('是否确定添加到书架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
       //最开始书籍为上架
      if(row.intestate==1){
        //(1)那么在上架中首先判断书籍是否存在在我的书架中
        //得出结论根据书籍id查询书架与书籍b_bs表 查询到 bsid 集合   /bookshelf/queryBookShelf
        var formData = new FormData();
        formData.append("bookId", row.id)
        formData.append("userId", this.user.id)
        axios({
          url: '/api/bookshelf/queryBookShelf',
          method: 'post',
          data: formData,
          headers:{"Authorization":"Bearer "+this.$store.state.user.token}
        }).then(res => {
          //(1)res.data.code 为状态码
          //如果状态码为1  那么说明书架中存在该书籍  如果状态码为0  那么说明书架中不存在该书籍
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '该书籍已在书架中'
            })
          }else if(res.data.code==0){
            //(2)如果不存在 那么就添加到书架
            //在添加到书架时应该注意 只能添加普通的书籍
            //如果为vip书籍时需要添加订单      row.vip=1为普通书籍  row.vip=2为vip书籍
            if(row.vip==1){
              // 调用添加书籍的接口
              this.addShelf(row)
              //添加成功添加到书架消息
              this.addMessages(row)
              this.getData()
            }else if(row.vip==2){
              //(3)判断是否订单是否存在在订单中
              //(3.5)创建axios接口用来根据bookId判断
              var data = new FormData();
              data.append("bookId", row.id)
              data.append("userId", this.user.id)
              axios({
                url: '/api/order/queryOrderState',
                method: 'post',
                data: data,
                headers:{"Authorization":"Bearer "+this.$store.state.user.token},
              }).then(res => {
                // console.log(res.data)
                // console.log(res.data.code)
                //说明订单存在,并且已经付过钱了,只是之前删除了
                //那么就直接添加书架
                if(res.data.code==1&&res.data.data==2){
                    this.addShelf(row)
                  //添加成功添加到书架消息
                    this.addMessages(row)
                }else if(res.data.code==1&&res.data.data==1){
                  //订单存在,但是还没有付钱
                    this.$message({
                      type: 'error',
                      message: '该书籍已存在订单中,请勿重新添加'
                    })
                }else if(res.data.code==0){
                  //调用添加订单的接口
                  this.AddOrder(row)
                  //添加成功添加到订单消息
                  this.addOrderMessages(row)
                }
              })
            }
          }

          console.log(res.data)


        })




        //根据bookid 查询表o_b中的orderId
        //根据orderId查询表order中的state(支付状态)

      }else if(row.intestate==2) {
        this.$message({
          type: 'error',
          message: '该书籍已下架'
        })

      }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加到书架'
        });
      });
    },
    // 修改书籍
    handleEdit(index, row) {
      // alert(row.id)
      // 使用路由的push方法  跳转到修改书籍页面
      this.$router.push({ name: 'BookEditView', query: { id: row.id }})
    },
    // 修改每页条数
    handleSizeChange(val) {
      this.pageInfo.pageSize = val
      this.getData()
    },
    // 修改当前页数
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val
      this.getData()
    },
    // 获取数据
    getData() {
      //获取所有的书籍类型
      axios({
        url: '/api/classification/queryAllCategory',
        method: 'post',
        headers:{"Authorization":"Bearer "+this.$store.state.user.token}
      }).then(res => {
        // console.log(res.data.data)
        this.options=res.data.data
      })

      var formData = new FormData();
      for (const arr in this.pageInfo) {
        formData.append(arr, this.pageInfo[arr])
      }
      formData.append("category", this.category)
      axios({
        //获取所有书籍信息
        url: '/api/book/queryAllBook',
        method: 'post',
        data: formData,
        headers:{"Authorization":"Bearer "+this.$store.state.user.token}
      }).then(res => {
        // console.log(res.data.data)
          this.book=res.data.data.list
        this.total = res.data.data.total

        //根据用户名查询用户信息
        var formData2 = new FormData();
        formData2.append("username", this.$store.state.user.name)
        axios({
          //根据用户名查询用户的个人信息
          url: '/api/user/queryUser',
          method: 'post',
          data: formData2,
          headers:{"Authorization":"Bearer "+this.$store.state.user.token}
        }).then(res => {
          this.user = res.data.data
        })
      })
    },
    //添加添加书架消息的接口
    addMessages(row){
      var formData = new FormData();
      formData.append("messages", row.bookName+"已经添加到书架中了,详情请移步到书架")
      formData.append("ids", this.user.id)
      axios({
        url: '/api/messages/addMessageByUser',
        method: 'post',
        data: formData,
        headers:{"Authorization":"Bearer "+this.$store.state.user.token}
      })
    },
    //添加添加订单消息的接口
    addOrderMessages(row){
      var formData = new FormData();
      formData.append("messages", row.bookName+"已经添加到订单中了,详情请移步到我的订单查看详情")
      formData.append("ids", this.user.id)
      axios({
        url: '/api/messages/addMessageByUser',
        method: 'post',
        data: formData,
        headers:{"Authorization":"Bearer "+this.$store.state.user.token}
      })
    },

    //添加书籍的接口
    addShelf(row){
      var formData = new FormData();
      formData.append("id", row.id)
      // formData.append("bookshelf", this.bookshelf)
      // formData.append("userId", this.user.id)
      // formData.append("category", row.category)
      for (const key in row) {
        // console.log(key)
        // console.log(row[key])
        formData.append(key, row[key])
      }
      axios({
        url: '/api/bookshelf/add/'+this.user.id,
        method: 'post',
        data:formData,
        headers:{"Authorization":"Bearer "+this.$store.state.user.token},
      }).then(res => {
        if (res.data.code ==1) {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        }
      })
    },
//添加订单的接口
    AddOrder(row){
      var formData = new FormData();
      formData.append("bookId",row.id)
      formData.append("state",this.orderState)
      formData.append("userId",this.user.id)
      for (const key in row) {
        formData.append(key, row[key])
      }
      axios({
        url: '/api/order/addOrder',
        method: 'post',
        data:formData,
        headers:{"Authorization":"Bearer "+this.$store.state.user.token},
      }).then(res => {
        if (res.data.code ==1) {
          this.$message({
            message: '添加订单成功',
            type:'success'
          })
          this.getData()
        } else {
          this.$message({
            message: '添加订单失败',
            type: 'error'
          })
        }
      })


    },


    // 查询
    onSubmit() {
        // alert(this.pageInfo.username)
      this.pageInfo.pageNum = 1 // 点击查询时  页码重置为1
      this.getData()
    },
    // 添加新角色
    onAdd() {
      this.$router.push('/novel/bookAddView')
    },
    // 删除医生信息
    handleDelete(index, row) {
      // get post
      if (confirm('确定要删除吗')) {
        axios({
          url: '/api/book/delete/' + row.id,
          method: 'post',
          headers:{"Authorization":"Bearer "+this.$store.state.user.token}
        }).then(res => {
          if (res.data.code == 1) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // 更新本页数据
            this.getData()
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            })



          }
        })


        // axios.get('/api/role/del/' + row.id)
        //   .then(res => {
        //     if (res.data.code == 1) {
        //       this.$message({
        //         message: '删除成功',
        //         type: 'success'
        //       })
        //       // 更新本页数据
        //       this.getData()
        //     } else {
        //       this.$message.error('删除失败')
        //     }
        //   })
      }
    }
    // this.$router.push({name:})
  }


}
</script>

<style scoped>

</style>
